using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.NetduinoPlus;

namespace CodingSmackdown.Services
{
    public class TemperatureLoggingService : ServiceBase
    {
        protected override void Run()
        {
            while (true)
            {
                try
                {
                    using (StreamWriter file = new StreamWriter(@"\SD\" + SystemSettings.HistoryFilename, true))
                    {
                        DateTime recordTime = DateTime.Now;
                        file.Write(recordTime.ToString());

                        float totalReading = 0;

                        for (int i = 0; i < 100; i++)
                        {
                            totalReading += PinManagement.GetAnalogPinValue(0);
                            Thread.Sleep(10);
                        }

                        float averageReading = totalReading / 100;

                        file.Write("," + averageReading.ToString());

                        float milliVolts = averageReading * 3300 / 1023;
                        file.Write("," + milliVolts.ToString());
                        float tempCelsius = (milliVolts - 500) / 10;
                        file.Write("," + tempCelsius.ToString());
                        float tempFahrenheit = ((tempCelsius * 9) / 5) + 32;
                        file.WriteLine("," + tempFahrenheit.ToString());
                    }
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine(ex.Message);
                }

                Thread.Sleep(SystemSettings.MinutesBetweenReadings);
            }
        }
    }
}
